package com.chuji.crmcj.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.chuji.crmcj.R;
import com.chuji.crmcj.act.NoticeDetailAct;
import com.chuji.crmcj.bean.MagSendNoticesInfo;
import com.chuji.crmcj.utils.SPUtils;
import com.chuji.crmcj.utils.UIUtils;
import com.chuji.crmcj.utils.UrlUtils;
import com.chuji.crmcj.utils.VolleyUtil;

import java.util.ArrayList;
import java.util.List;


public class MagSendNoticeFragment extends Fragment {

    /*通知布局*/
    private ListView lv_send_notice;
    /*自定义适配器*/
    private CustomSendNoticeClientAdapter customSendNoticeClientAdapter;
    /*数据存储*/
    List<MagSendNoticesInfo.ApiParamObjEntity> magSendNoticesData;
    /*网络数据*/
    private MagSendNoticesInfo magSendNoticesInfo;
    //用户ID
    String UserID;
    Intent intent;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mag_send_notice, container, false);
        lv_send_notice = (ListView) view.findViewById(R.id.lv_send_notice);
        initData();
//        //下拉刷新
//        lv_send_notice.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
//            @Override
//            public void onRefresh(
//                    PullToRefreshBase<ListView> refreshView) {
//                initData();
//            }
//        });
        return view;
    }

    private void initData() {
        //第一次
        if (magSendNoticesData == null) {
            magSendNoticesData = new ArrayList<MagSendNoticesInfo.ApiParamObjEntity>();
        }
        requestData();
    }

    private void requestData() {
        //初始化Volley
        UserID = SPUtils.getString(UIUtils.getContext(), "UserID", "");
        String strURL = String.format(UrlUtils.MAG_NOTICE_FORM + "&UserID=" + UserID + "&isReceive=0");
        StringRequest stringRequest = new StringRequest(Request.Method.GET, strURL, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                magSendNoticesInfo = JSON.parseObject(response, MagSendNoticesInfo.class);
                magSendNoticesData.addAll(magSendNoticesInfo.getApiParamObj());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        // 判断adapter是否创建
                        if (customSendNoticeClientAdapter == null) {
                            customSendNoticeClientAdapter = new CustomSendNoticeClientAdapter();
                            lv_send_notice.setAdapter(customSendNoticeClientAdapter);
                        } else {
                            customSendNoticeClientAdapter.notifyDataSetChanged();
                        }
                        //给ListView设置点击事件
                        lv_send_notice.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                                //传递消息ID
                                Intent intent = new Intent(UIUtils.getContext(), NoticeDetailAct.class);
                                intent.putExtra("MessageID", magSendNoticesData.get(position).getMessageID());
                                System.out.println(magSendNoticesData.get(position).getMessageID() + "------------------------------------");
                                startActivity(intent);
                            }
                        });
                    }
                });
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
                System.out.println("失败" + error);
                UIUtils.showToastSafe("请检查网络");
            }
        });
        // Add the request to the RequestQueue.
        VolleyUtil.getRequestQueue().add(stringRequest);
    }

    /**
     * 自定义适配器
     */
    class CustomSendNoticeClientAdapter extends BaseAdapter {

        private Context context;

        @Override
        public int getCount() {
            return magSendNoticesData.size();
        }

        @Override
        public Object getItem(int i) {
            return magSendNoticesData.get(i);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup viewGroup) {
            /****1)根据list_item.xml--》得到当前子项元素的布局   【界面】*******/
            //b)声明ViewHolder
            ViewHolder viewHolder = null;
            //c)判断convertView是否为null
            if (convertView == null) {//第一次调用getView（）方法时为 null,意思就是在内存中没有
                viewHolder = new ViewHolder();
                convertView = LayoutInflater.from(UIUtils.getContext()).inflate(R.layout.mag_listview_send_notice, null);
                //初始化组件
                viewHolder.mTv_notice_title = (TextView) convertView.findViewById(R.id.tv_notice_title);
                viewHolder.mTv_notice_time = (TextView) convertView.findViewById(R.id.tv_notice_time);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            if (magSendNoticesData.size() != 0) {
                viewHolder.mTv_notice_title.setText(magSendNoticesData.get(0).getTitle());
                viewHolder.mTv_notice_time.setText(magSendNoticesData.get(0).getSendTime());
            } else {
                UIUtils.showToastSafe("暂无数据");
            }
            return convertView;
        }
    }

    static class ViewHolder {

        private TextView mTv_notice_title;
        private TextView mTv_notice_time;

    }
}
